<template>
  <div class="building-container">
    <div class="person-container">
      <LeftMenu />
      <div class="building-content">
        <el-card>
          <ManagementTitle>
            <template #title>
              楼栋房源列表 - {{ buildingInfo.name || '' }}栋
              <el-button size="small" @click="goBack" style="margin-left: 16px;">返回楼栋列表</el-button>
            </template>
          </ManagementTitle>

          <!-- 楼栋基本信息 -->
          <div class="building-info-card">
            <el-card shadow="never" class="info-card">
              <div class="building-info">
                <div class="info-details">
                  <div class="detail-row">
                    <div class="detail-item">
                      <span class="detail-label">所属小区：</span>
                      <span class="detail-value">{{ plotName }}</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">楼栋名称：</span>
                      <span class="detail-value">{{ buildingInfo.name }}栋</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">单元数：</span>
                      <span class="detail-value">{{ buildingInfo.unitNum }}个</span>
                    </div>
                  </div>
                  <div class="detail-row">
                    <div class="detail-item">
                      <span class="detail-label">楼层数：</span>
                      <span class="detail-value">{{ buildingInfo.floorNum }}层</span>
                    </div>
                    <div class="detail-item">
                      <span class="detail-label">总房源数：</span>
                      <span class="detail-value">{{ buildingInfo.totalHouses }}套</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 操作按钮区域 -->
          <div class="building-header" v-if="selectedHouses.length > 0">
            <div class="batch-info">
              <span class="selected-count">已选择 {{ selectedHouses.length }} 套房源</span>
            </div>
            <el-button type="primary" @click="handleBatchEdit">
              <el-icon><Edit /></el-icon>
              批量编辑
            </el-button>
            <el-button @click="clearSelection">
              <el-icon><Close /></el-icon>
              取消选择
            </el-button>
          </div>

          <!-- 选择控制区域 -->
          <div class="selection-controls">
            <el-checkbox
              v-model="selectAll"
              @change="handleSelectAll"
              :indeterminate="isIndeterminate"
            >
              全选房源
            </el-checkbox>
            <span class="selection-info">已选择 {{ selectedHouses.length }} 套房源</span>
          </div>

          <!-- 房源列表区域 -->
          <div class="house-list-container" v-loading="loading">
            <div v-if="buildingInfo.map && Object.keys(buildingInfo.map).length > 0" class="units-container">
              <!-- 单元循环 -->
              <div
                v-for="(unitData, unitNum) in buildingInfo.map"
                :key="unitNum"
                class="unit-section"
              >
                <div class="unit-title">
                  <h3>{{ unitNum }}单元</h3>
                  <el-checkbox
                    :model-value="isUnitSelected(String(unitNum))"
                    @change="(val: boolean) => handleUnitSelect(String(unitNum), val)"
                    :indeterminate="isUnitIndeterminate(String(unitNum))"
                  >
                    选择整个单元
                  </el-checkbox>
                </div>

                <!-- 楼层表格 -->
                <el-table
                  :data="getUnitFloorData(unitData, String(unitNum))"
                  border
                  class="floor-table"
                  :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
                >
                  <el-table-column label="楼层" width="80" align="center">
                    <template #default="{ row }">
                      <div class="floor-cell">
                        <el-checkbox
                          :model-value="isFloorSelected(String(unitNum), row.floorNum)"
                          @change="(val: boolean) => handleFloorSelect(String(unitNum), row.floorNum, val)"
                          :indeterminate="isFloorIndeterminate(String(unitNum), row.floorNum)"
                          size="small"
                        />
                        <span>{{ row.floorNum }}层</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="房源" min-width="200">
                    <template #default="{ row }">
                      <div class="houses-row" :style="getHousesRowStyle(row.houses.length)">
                        <div
                          v-for="house in row.houses"
                          :key="house.id"
                          class="house-cell"
                          :class="{
                            'selected': selectedHouses.includes(house.id),
                            'occupied': house.state === 1
                          }"
                          :style="getHouseCellStyle(row.houses.length)"
                          @click="handleHouseSelect(house.id)"
                        >
                          <el-checkbox
                            :model-value="selectedHouses.includes(house.id)"
                            @change="(val: boolean) => handleHouseCheckboxChange(house.id, val)"
                            @click.stop
                            size="small"
                          />
                          <span class="house-number" @click.stop="showHouseDetail(house)">{{ house.num }}</span>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-empty description="该楼栋暂无房源数据" />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 房源详情侧滑面板 -->
    <el-drawer
      v-model="showHouseDetailDrawer"
      title="房源详情"
      direction="rtl"
      size="500px"
      :before-close="handleDrawerClose"
    >
      <div v-if="currentHouse" class="house-detail-content">
        <el-form :model="houseDetailForm" label-width="100px" ref="houseDetailFormRef">
          <el-form-item label="房号">
            <el-input v-model="houseDetailForm.num" disabled />
          </el-form-item>
          
          <el-form-item label="户型">
            <el-input v-model="houseDetailForm.type" placeholder="请输入户型，如：三室两厅一卫" />
          </el-form-item>
          
          <el-form-item label="面积(㎡)">
            <el-input-number v-model="houseDetailForm.area" :min="0" style="width: 100%" />
          </el-form-item>
          
          <el-form-item label="租金(元/月)">
            <el-input-number v-model="houseDetailForm.rent" :min="0" style="width: 100%" />
          </el-form-item>
          
          <el-form-item label="房屋用途">
            <el-select v-model="houseDetailForm.houseUse" style="width: 100%">
              <el-option label="住宅" :value="1" />
              <el-option label="公寓" :value="2" />
              <el-option label="办公" :value="3" />
              <el-option label="商铺" :value="4" />
              <el-option label="写字楼" :value="5" />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁类型">
            <el-select v-model="houseDetailForm.rentalType" style="width: 100%">
              <el-option label="整租" :value="1" />
              <el-option label="分租" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="房源权属">
            <el-select v-model="houseDetailForm.ownershipType" style="width: 100%">
              <el-option label="企业" :value="0" />
              <el-option label="个人" :value="1" />
              <el-option label="居间" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="装修类型">
            <el-select v-model="houseDetailForm.decoration" style="width: 100%">
              <el-option label="毛坯" :value="1" />
              <el-option label="简装" :value="2" />
              <el-option label="精装" :value="3" />
              <el-option label="豪装" :value="4" />
              <el-option label="其他" :value="5" />
            </el-select>
          </el-form-item>

          <el-form-item label="支付类型">
            <el-select v-model="houseDetailForm.payType" style="width: 100%">
              <el-option label="付一押一" :value="1" />
              <el-option label="付一押二" :value="2" />
              <el-option label="付一押三" :value="3" />
              <el-option label="付二押一" :value="4" />
              <el-option label="付三押一" :value="5" />
              <el-option label="付三押二" :value="6" />
              <el-option label="月付" :value="7" />
              <el-option label="半年付" :value="8" />
            </el-select>
          </el-form-item>

          <el-form-item label="朝向">
            <el-select v-model="houseDetailForm.orientation" style="width: 100%">
              <el-option label="东" :value="1" />
              <el-option label="南" :value="2" />
              <el-option label="西" :value="3" />
              <el-option label="北" :value="4" />
            </el-select>
          </el-form-item>

          <el-form-item label="所在楼层">
            <el-select v-model="houseDetailForm.floor" style="width: 100%">
              <el-option label="低层" :value="1" />
              <el-option label="中层" :value="2" />
              <el-option label="高层" :value="3" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="房屋状态">
            <el-tag :type="getStatusTagType(houseDetailForm.state)">
              {{ getStatusText(houseDetailForm.state) }}
            </el-tag>
          </el-form-item>
          
          <el-form-item label="房屋标题">
            <el-input v-model="houseDetailForm.title" type="textarea" :rows="2" />
          </el-form-item>
          
          <el-form-item label="几居室">
            <el-input-number v-model="houseDetailForm.typeNum" :min="0" style="width: 100%" />
          </el-form-item>

          <el-form-item label="区域">
            <el-select v-model="houseDetailForm.region" placeholder="请选择区域" style="width: 100%">
              <el-option
                v-for="county in allCounties"
                :key="county.id"
                :label="county.name"
                :value="county.name"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址">
            <el-input v-model="houseDetailForm.address" />
          </el-form-item>

          <el-form-item label="配套设施">
            <div class="facility-selection">
              <el-checkbox-group v-model="selectedFacilityIds" @change="onFacilityChange">
                <el-checkbox
                  v-for="facility in allFacilities"
                  :key="facility.id"
                  :label="facility.id"
                  class="facility-checkbox"
                >
                  {{ facility.name }}
                </el-checkbox>
              </el-checkbox-group>
              <div class="facility-preview" v-if="houseDetailForm.facilities">
                <small class="text-muted">存储格式预览：{{ houseDetailForm.facilities }}</small>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="房东要求">
            <el-input v-model="houseDetailForm.need" type="textarea" :rows="2" />
          </el-form-item>

          <el-form-item label="房源描述">
            <el-input v-model="houseDetailForm.description" type="textarea" :rows="3" />
          </el-form-item>

          <el-form-item label="房源图片">
            <div class="house-image-upload">
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                :file-list="houseImageList"
                :on-success="handleHouseImageSuccess"
                :on-remove="handleHouseImageRemove"
                :on-error="handleHouseImageError"
                :before-upload="beforeHouseImageUpload"
                list-type="picture-card"
                accept="image/*"
                :limit="10"
                :disabled="uploadLoading"
              >
                <el-icon v-if="!uploadLoading"><Plus /></el-icon>
                <el-icon v-else class="is-loading"><Loading /></el-icon>
              </el-upload>
              <div class="upload-tip">
                <small class="text-muted">支持jpg、png、gif等格式，最多上传10张图片，每张图片不超过5MB</small>
              </div>
              <div class="image-urls-preview" v-if="houseDetailForm.imageUrls">
                <small class="text-muted">存储格式：{{ houseDetailForm.imageUrls }}</small>
              </div>
            </div>
          </el-form-item>
        </el-form>
        
        <div class="drawer-footer">
          <el-button @click="handleDrawerClose">取消</el-button>
          <el-button type="primary" @click="saveHouseDetail" :loading="saveLoading">保存修改</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 批量编辑对话框 -->
    <el-dialog
      v-model="showBatchEditDialog"
      title="批量编辑房源"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-edit-info">
        <el-alert
          :title="`将对 ${selectedHouses.length} 套房源进行批量编辑`"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        />
      </div>
      
      <el-form :model="batchEditForm" label-width="100px" ref="batchEditFormRef">
        <el-form-item label="房源标题">
          <el-input v-model="batchEditForm.title" placeholder="留空表示不修改" />
        </el-form-item>

        <el-form-item label="户型">
          <el-select v-model="batchEditForm.type" placeholder="请选择户型（留空表示不修改）" style="width: 100%" clearable>
            <el-option
              v-for="type in buildingTypes"
              :key="type.id"
              :label="type.name"
              :value="type.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="面积(㎡)">
          <el-input-number v-model="batchEditForm.area" :min="0" placeholder="留空表示不修改" style="width: 100%" />
        </el-form-item>

        <el-form-item label="租金(元/月)">
          <el-input-number v-model="batchEditForm.rent" :min="0" placeholder="留空表示不修改" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="房屋用途">
          <el-select v-model="batchEditForm.houseUse" placeholder="请选择（留空表示不修改）" style="width: 100%" clearable>
            <el-option label="住宅" :value="1" />
            <el-option label="公寓" :value="2" />
            <el-option label="办公" :value="3" />
            <el-option label="商铺" :value="4" />
            <el-option label="写字楼" :value="5" />
          </el-select>
        </el-form-item>

        <el-form-item label="租赁类型">
          <el-select v-model="batchEditForm.rentalType" placeholder="请选择（留空表示不修改）" style="width: 100%" clearable>
            <el-option label="整租" :value="1" />
            <el-option label="分租" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="房源权属">
          <el-select v-model="batchEditForm.ownershipType" placeholder="请选择（留空表示不修改）" style="width: 100%" clearable>
            <el-option label="企业" :value="0" />
            <el-option label="个人" :value="1" />
            <el-option label="居间" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="装修类型">
          <el-select v-model="batchEditForm.decoration" placeholder="请选择（留空表示不修改）" style="width: 100%" clearable>
            <el-option label="毛坯" :value="1" />
            <el-option label="简装" :value="2" />
            <el-option label="精装" :value="3" />
            <el-option label="豪装" :value="4" />
            <el-option label="其他" :value="5" />
          </el-select>
        </el-form-item>

        <el-form-item label="支付类型">
          <el-select v-model="batchEditForm.payType" placeholder="请选择（留空表示不修改）" style="width: 100%" clearable>
            <el-option label="付一押一" :value="1" />
            <el-option label="付一押二" :value="2" />
            <el-option label="付一押三" :value="3" />
            <el-option label="付二押一" :value="4" />
            <el-option label="付三押一" :value="5" />
            <el-option label="付三押二" :value="6" />
            <el-option label="月付" :value="7" />
            <el-option label="半年付" :value="8" />
          </el-select>
        </el-form-item>

        <el-form-item label="朝向">
          <el-select v-model="batchEditForm.orientation" placeholder="请选择（留空表示不修改）" style="width: 100%" clearable>
            <el-option label="东" :value="1" />
            <el-option label="南" :value="2" />
            <el-option label="西" :value="3" />
            <el-option label="北" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="所在楼层">
          <el-select v-model="batchEditForm.floor" placeholder="请选择（留空表示不修改）" style="width: 100%" clearable>
            <el-option label="低层" :value="1" />
            <el-option label="中层" :value="2" />
            <el-option label="高层" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="几居室">
          <el-input-number v-model="batchEditForm.typeNum" :min="0" placeholder="留空表示不修改" style="width: 100%" />
        </el-form-item>

        <el-form-item label="区域">
          <el-select v-model="batchEditForm.region" placeholder="留空表示不修改" style="width: 100%" clearable>
            <el-option
              v-for="county in allCounties"
              :key="county.id"
              :label="county.name"
              :value="county.name"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input v-model="batchEditForm.address" placeholder="留空表示不修改" />
        </el-form-item>

        <el-form-item label="配套设施">
          <div class="facility-selection">
            <el-checkbox-group v-model="batchSelectedFacilityIds" @change="onBatchFacilityChange">
              <el-checkbox
                v-for="facility in allFacilities"
                :key="facility.id"
                :label="facility.id"
                class="facility-checkbox"
              >
                {{ facility.name }}
              </el-checkbox>
            </el-checkbox-group>
            <div class="facility-preview" v-if="batchEditForm.facilities">
              <small class="text-muted">存储格式预览：{{ batchEditForm.facilities }}</small>
            </div>
            <div class="facility-hint">
              <small class="text-muted">提示：留空表示不修改此字段</small>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="房东要求">
          <el-input v-model="batchEditForm.need" type="textarea" :rows="2" placeholder="留空表示不修改" />
        </el-form-item>

        <el-form-item label="房源描述">
          <el-input v-model="batchEditForm.description" type="textarea" :rows="3" placeholder="留空表示不修改" />
        </el-form-item>

        <el-form-item label="房源图片">
          <div class="house-image-upload">
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :file-list="batchImageList"
              :on-success="handleBatchImageSuccess"
              :on-remove="handleBatchImageRemove"
              :on-error="handleBatchImageError"
              :before-upload="beforeBatchImageUpload"
              list-type="picture-card"
              accept="image/*"
              :limit="10"
              :disabled="uploadLoading"
            >
              <el-icon v-if="!uploadLoading"><Plus /></el-icon>
              <el-icon v-else class="is-loading"><Loading /></el-icon>
            </el-upload>
            <div class="upload-tip">
              <small class="text-muted">批量设置房源图片，留空表示不修改此字段</small>
            </div>
            <div class="image-urls-preview" v-if="batchEditForm.imageUrls">
              <small class="text-muted">存储格式：{{ batchEditForm.imageUrls }}</small>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showBatchEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleBatchEditSubmit" :loading="batchEditLoading">确定修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Close, Plus, Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import LeftMenu from '@/user/LeftMenu.vue'
import ManagementTitle from '@/components/ManagementTitle.vue'

// 路由参数
const route = useRoute()
const buildingId = ref(route.query.buildingId as string)
const buildingName = ref(route.query.buildingName as string || '')
const plotName = ref(route.query.plotName as string || '')

// 响应式数据
const loading = ref(false)
const buildingInfo = ref<any>({})
const selectedHouses = ref<string[]>([])

// 房源详情侧滑面板
const showHouseDetailDrawer = ref(false)
const currentHouse = ref<any>(null)
const saveLoading = ref(false)
const houseDetailForm = ref<any>({})
const houseDetailFormRef = ref()

// 批量编辑
const showBatchEditDialog = ref(false)
const batchEditLoading = ref(false)
const batchEditForm = ref<any>({})
const batchEditFormRef = ref()

// 楼栋户型列表
const buildingTypes = ref<any[]>([])

// 配套设施相关
const allFacilities = ref<any[]>([])
const selectedFacilityIds = ref<number[]>([])
const batchSelectedFacilityIds = ref<number[]>([])

// 区域相关
const allCounties = ref<any[]>([])

// 图片上传相关
const uploadUrl = ref('http://127.0.0.1:8080/oss/file/upload') // 使用现有的OSS上传接口，正确路径
const uploadHeaders = ref({
  'Authorization': 'Bearer ' + localStorage.getItem('token') // 根据实际情况调整
})
const uploadLoading = ref(false)
const houseImageList = ref<any[]>([])
const batchImageList = ref<any[]>([])

// 全选相关
const selectAll = ref(false)
const isIndeterminate = computed(() => {
  const totalHouses = getAllHouses().length
  const selectedCount = selectedHouses.value.length
  return selectedCount > 0 && selectedCount < totalHouses
})

const getAllHouses = () => {
  const houses: any[] = []
  if (buildingInfo.value.map) {
    Object.values(buildingInfo.value.map).forEach((unitData: any) => {
      Object.values(unitData).forEach((floorData: any) => {
        houses.push(...floorData)
      })
    })
  }
  return houses
}

const handleSelectAll = (checked: boolean) => {
  if (checked) {
    const allHouses = getAllHouses()
    selectedHouses.value = allHouses.map(house => house.id)
  } else {
    selectedHouses.value = []
  }
}

// 获取楼栋详情
const getBuildingDetails = async () => {
  if (!buildingId.value) return

  try {
    loading.value = true
    const timestamp = new Date().getTime()
    const response = await axios.get(`/rental/areabuilding/getBuildingById/${buildingId.value}?t=${timestamp}`)

    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      const directResponse = await axios.get(`http://127.0.0.1:8081/rental/areabuilding/getBuildingById/${buildingId.value}?t=${timestamp}`)

      if (directResponse.data.code === 0) {
        buildingInfo.value = directResponse.data.data || {}
        console.log('楼栋详情数据:', buildingInfo.value)
      } else {
        ElMessage.error(directResponse.data.msg || '获取楼栋详情失败')
      }
    } else if (response.data.code === 0) {
      buildingInfo.value = response.data.data || {}
      console.log('楼栋详情数据:', buildingInfo.value)
    } else {
      ElMessage.error(response.data.msg || '获取楼栋详情失败')
    }
  } catch (error) {
    console.error('获取楼栋详情失败:', error)
    ElMessage.error('获取楼栋详情失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 表格数据处理函数
const getUnitFloorData = (unitData: any, unitNum: string) => {
  const floorData: any[] = []

  Object.keys(unitData).forEach(floorNum => {
    floorData.push({
      floorNum: floorNum,
      houses: unitData[floorNum] || []
    })
  })

  // 按楼层号排序（数字排序）
  return floorData.sort((a, b) => parseInt(b.floorNum) - parseInt(a.floorNum))
}

// 返回上一页
const goBack = () => {
  window.close()
}

// 页面初始化
onMounted(() => {
  console.log('房源列表详情页面初始化')
  console.log('楼栋ID:', buildingId.value)
  console.log('楼栋名称:', buildingName.value)
  console.log('小区名称:', plotName.value)

  getBuildingDetails()
  loadAllFacilities()
  loadAllCounties()
})

// 房源选择相关函数
const handleHouseSelect = (houseId: any) => {
  const index = selectedHouses.value.indexOf(houseId)
  if (index > -1) {
    selectedHouses.value.splice(index, 1)
  } else {
    selectedHouses.value.push(houseId)
  }
}

const handleHouseCheckboxChange = (houseId: any, checked: boolean) => {
  if (checked) {
    if (!selectedHouses.value.includes(houseId)) {
      selectedHouses.value.push(houseId)
    }
  } else {
    const index = selectedHouses.value.indexOf(houseId)
    if (index > -1) {
      selectedHouses.value.splice(index, 1)
    }
  }
}

const clearSelection = () => {
  selectedHouses.value = []
}

// 单元选择相关
const isUnitSelected = (unitNum: string) => {
  const unitHouses = getUnitHouses(unitNum)
  return unitHouses.length > 0 && unitHouses.every(house => selectedHouses.value.includes(house.id))
}

const isUnitIndeterminate = (unitNum: string) => {
  const unitHouses = getUnitHouses(unitNum)
  const selectedCount = unitHouses.filter(house => selectedHouses.value.includes(house.id)).length
  return selectedCount > 0 && selectedCount < unitHouses.length
}

const handleUnitSelect = (unitNum: string, checked: boolean) => {
  const unitHouses = getUnitHouses(unitNum)

  if (checked) {
    // 选择该单元的所有房源
    unitHouses.forEach(house => {
      if (!selectedHouses.value.includes(house.id)) {
        selectedHouses.value.push(house.id)
      }
    })
  } else {
    // 取消选择该单元的所有房源
    unitHouses.forEach(house => {
      const index = selectedHouses.value.indexOf(house.id)
      if (index > -1) {
        selectedHouses.value.splice(index, 1)
      }
    })
  }
}

// 楼层选择相关
const isFloorSelected = (unitNum: string, floorNum: string) => {
  const floorHouses = getFloorHouses(unitNum, floorNum)
  return floorHouses.length > 0 && floorHouses.every((house: any) => selectedHouses.value.includes(house.id))
}

const isFloorIndeterminate = (unitNum: string, floorNum: string) => {
  const floorHouses = getFloorHouses(unitNum, floorNum)
  const selectedCount = floorHouses.filter((house: any) => selectedHouses.value.includes(house.id)).length
  return selectedCount > 0 && selectedCount < floorHouses.length
}

const handleFloorSelect = (unitNum: string, floorNum: string, checked: boolean) => {
  const floorHouses = getFloorHouses(unitNum, floorNum)

  if (checked) {
    // 选择该楼层的所有房源
    floorHouses.forEach((house: any) => {
      if (!selectedHouses.value.includes(house.id)) {
        selectedHouses.value.push(house.id)
      }
    })
  } else {
    // 取消选择该楼层的所有房源
    floorHouses.forEach((house: any) => {
      const index = selectedHouses.value.indexOf(house.id)
      if (index > -1) {
        selectedHouses.value.splice(index, 1)
      }
    })
  }
}

// 辅助函数
const getUnitHouses = (unitNum: string) => {
  const houses: any[] = []
  if (buildingInfo.value.map && buildingInfo.value.map[unitNum]) {
    Object.values(buildingInfo.value.map[unitNum]).forEach((floorData: any) => {
      houses.push(...floorData)
    })
  }
  return houses
}

const getFloorHouses = (unitNum: string, floorNum: string) => {
  if (buildingInfo.value.map && buildingInfo.value.map[unitNum] && buildingInfo.value.map[unitNum][floorNum]) {
    return buildingInfo.value.map[unitNum][floorNum]
  }
  return []
}

// 样式相关函数
const getHousesRowStyle = (houseCount: number) => {
  return {
    display: 'flex',
    flexWrap: 'wrap' as const,
    gap: '8px',
    minHeight: '40px',
    alignItems: 'center'
  }
}

const getHouseCellStyle = (houseCount: number) => {
  const baseWidth = Math.max(60, Math.min(120, 800 / houseCount))
  return {
    minWidth: `${baseWidth}px`,
    maxWidth: `${baseWidth + 20}px`
  }
}

// 状态相关函数
const getStatusText = (state: number) => {
  switch (state) {
    case 0: return '空闲'
    case 1: return '已租'
    case 2: return '已删除'
    default: return '未知'
  }
}

const getStatusTagType = (state: number) => {
  switch (state) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

// 房源详情相关
const showHouseDetail = async (house: any) => {
  currentHouse.value = house
  houseDetailForm.value = { ...house }
  showHouseDetailDrawer.value = true

  // 获取楼栋户型列表
  await getBuildingTypes()

  // 解析配套设施
  if (house.facilities) {
    selectedFacilityIds.value = await parseFacilitiesFromString(house.facilities)
  } else {
    selectedFacilityIds.value = []
  }

  // 加载房源图片列表
  updateHouseImageList()
}

const getBuildingTypes = async () => {
  try {
    const response = await axios.get(`/rental/areaplottype/TypeidAndName/${buildingId.value}`)
    if (response.data.code === 0) {
      buildingTypes.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取户型列表失败:', error)
  }
}

// 配套设施相关方法
const loadAllFacilities = async () => {
  try {
    const response = await axios.get('/rental/housefacility/all')
    if (response.data.code === 0) {
      allFacilities.value = response.data.data || []
      console.log('配套设施列表:', allFacilities.value)
    } else {
      ElMessage.error('获取配套设施列表失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('获取配套设施列表失败:', error)
    ElMessage.error('获取配套设施列表失败，请检查网络连接')
  }
}

const parseFacilitiesFromString = async (facilitiesStr: string) => {
  if (!facilitiesStr) return []

  try {
    const response = await axios.post(`/rental/areaplothouse/parseFacilities?facilitiesStr=${encodeURIComponent(facilitiesStr)}`)
    if (response.data.code === 0) {
      return response.data.data || []
    }
  } catch (error) {
    console.error('解析配套设施失败:', error)
  }
  return []
}

const convertFacilitiesToString = async (facilityIds: number[]) => {
  if (!facilityIds || facilityIds.length === 0) return ''

  try {
    const response = await axios.post('/rental/areaplothouse/convertFacilities', {
      facilityIds: facilityIds
    })
    if (response.data.code === 0) {
      return response.data.data || ''
    }
  } catch (error) {
    console.error('转换配套设施失败:', error)
  }
  return ''
}

const onFacilityChange = async () => {
  const facilitiesStr = await convertFacilitiesToString(selectedFacilityIds.value)
  houseDetailForm.value.facilities = facilitiesStr
}

const onBatchFacilityChange = async () => {
  const facilitiesStr = await convertFacilitiesToString(batchSelectedFacilityIds.value)
  batchEditForm.value.facilities = facilitiesStr
}

// 区域相关方法
const loadAllCounties = async () => {
  try {
    const response = await axios.get('/rental/areacounty/getAllCounty')
    if (response.data.code === 0) {
      allCounties.value = response.data.data || []
      console.log('区域列表:', allCounties.value)
    } else {
      ElMessage.error('获取区域列表失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('获取区域列表失败:', error)
    ElMessage.error('获取区域列表失败，请检查网络连接')
  }
}

// 图片上传相关方法
const parseImageUrls = (imageUrlsStr: string): string[] => {
  if (!imageUrlsStr) return []
  return imageUrlsStr.split(',').filter(url => url.trim())
}

const formatImageUrls = (urls: string[]): string => {
  return urls.filter(url => url.trim()).join(',')
}

const updateHouseImageList = () => {
  const urls = parseImageUrls(houseDetailForm.value.imageUrls || '')
  houseImageList.value = urls.map((url, index) => ({
    uid: index,
    name: `image-${index + 1}`,
    status: 'done',
    url: url
  }))
}

const updateBatchImageList = () => {
  const urls = parseImageUrls(batchEditForm.value.imageUrls || '')
  batchImageList.value = urls.map((url, index) => ({
    uid: index,
    name: `image-${index + 1}`,
    status: 'done',
    url: url
  }))
}

// 房源详情图片上传
const beforeHouseImageUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  uploadLoading.value = true
  return true
}

const handleHouseImageSuccess = (response: any, file: any) => {
  uploadLoading.value = false
  if (response.code === 0) {
    const currentUrls = parseImageUrls(houseDetailForm.value.imageUrls || '')
    // OSS接口返回的是UploadDTO对象，包含url字段
    currentUrls.push(response.data.url)
    houseDetailForm.value.imageUrls = formatImageUrls(currentUrls)
    updateHouseImageList()
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败：' + response.msg)
  }
}

const handleHouseImageRemove = (file: any) => {
  const currentUrls = parseImageUrls(houseDetailForm.value.imageUrls || '')
  const filteredUrls = currentUrls.filter(url => url !== file.url)
  houseDetailForm.value.imageUrls = formatImageUrls(filteredUrls)
  updateHouseImageList()
}

const handleHouseImageError = (error: any) => {
  uploadLoading.value = false
  ElMessage.error('图片上传失败，请重试')
  console.error('图片上传错误:', error)
}

// 批量编辑图片上传
const beforeBatchImageUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  uploadLoading.value = true
  return true
}

const handleBatchImageSuccess = (response: any, file: any) => {
  uploadLoading.value = false
  if (response.code === 0) {
    const currentUrls = parseImageUrls(batchEditForm.value.imageUrls || '')
    // OSS接口返回的是UploadDTO对象，包含url字段
    currentUrls.push(response.data.url)
    batchEditForm.value.imageUrls = formatImageUrls(currentUrls)
    updateBatchImageList()
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败：' + response.msg)
  }
}

const handleBatchImageRemove = (file: any) => {
  const currentUrls = parseImageUrls(batchEditForm.value.imageUrls || '')
  const filteredUrls = currentUrls.filter(url => url !== file.url)
  batchEditForm.value.imageUrls = formatImageUrls(filteredUrls)
  updateBatchImageList()
}

const handleBatchImageError = (error: any) => {
  uploadLoading.value = false
  ElMessage.error('图片上传失败，请重试')
  console.error('图片上传错误:', error)
}

const handleDrawerClose = () => {
  showHouseDetailDrawer.value = false
  currentHouse.value = null
  houseDetailForm.value = {}
  selectedFacilityIds.value = []
  houseImageList.value = []
}

const saveHouseDetail = async () => {
  try {
    saveLoading.value = true
    const response = await axios.put(`/rental/areaplothouse/${currentHouse.value.id}`, houseDetailForm.value)

    if (response.data.code === 0) {
      ElMessage.success('房源信息更新成功')
      handleDrawerClose()
      await getBuildingDetails()
    } else {
      ElMessage.error(response.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('保存房源详情失败:', error)
    ElMessage.error('保存失败，请检查网络连接')
  } finally {
    saveLoading.value = false
  }
}

// 批量编辑相关
const handleBatchEdit = () => {
  if (selectedHouses.value.length === 0) {
    ElMessage.warning('请先选择要编辑的房源')
    return
  }

  batchEditForm.value = {
    imageUrls: '' // 初始化图片URL字段
  }
  batchSelectedFacilityIds.value = []
  batchImageList.value = []
  showBatchEditDialog.value = true
  getBuildingTypes()
}

const handleBatchEditSubmit = async () => {
  try {
    batchEditLoading.value = true

    const updateData = Object.keys(batchEditForm.value).reduce((acc, key) => {
      const value = batchEditForm.value[key]
      // 对于imageUrls字段，即使是空字符串也要包含（表示清空图片）
      if (key === 'imageUrls') {
        if (value !== null && value !== undefined) {
          acc[key] = value
        }
      } else {
        // 其他字段保持原有逻辑
        if (value !== null && value !== undefined && value !== '') {
          acc[key] = value
        }
      }
      return acc
    }, {} as any)

    if (Object.keys(updateData).length === 0) {
      ElMessage.warning('请至少选择一个要修改的字段')
      return
    }

    const requestData = {
      houseIds: selectedHouses.value,
      updateData: updateData
    }

    const response = await axios.put('/rental/areaplothouse/batch', requestData)

    if (response.data.code === 0) {
      ElMessage.success(`成功批量更新 ${selectedHouses.value.length} 套房源`)
      showBatchEditDialog.value = false
      selectedHouses.value = []
      await getBuildingDetails()
    } else {
      ElMessage.error(response.data.msg || '批量更新失败')
    }
  } catch (error) {
    console.error('批量编辑失败:', error)
    ElMessage.error('批量编辑失败，请检查网络连接')
  } finally {
    batchEditLoading.value = false
  }
}

// 移除了批量删除和添加房源功能
</script>

<style scoped>
.building-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.person-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.building-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  min-width: 0;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.building-info-card {
  margin-bottom: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.building-info {
  padding: 0;
}

.info-details {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-row {
  display: flex;
  gap: 32px;
  flex-wrap: wrap;
}

.detail-item {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.detail-item.full-width {
  min-width: 100%;
}

.detail-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
  white-space: nowrap;
}

.detail-value {
  color: #303133;
  font-weight: 600;
}

.building-header {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.batch-info {
  display: flex;
  align-items: center;
  margin-right: 16px;
}

.selected-count {
  background: #e6f7ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.selection-controls {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.selection-info {
  color: #606266;
  font-size: 14px;
}

.house-list-container {
  background-color: #fff;
  border-radius: 6px;
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
  overflow-x: auto;
}

.units-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  width: 100%;
  box-sizing: border-box;
}

.unit-section {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  flex: 1 1 calc(50% - 10px);
  min-width: 350px;
  max-width: calc(50% - 10px);
  box-sizing: border-box;
}

.unit-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.unit-title h3 {
  margin: 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}

.floor-table {
  width: 100%;
  table-layout: fixed;
}

.floor-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.houses-row {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 40px;
  align-items: center;
  padding: 8px 0;
}

.house-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px 4px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  flex: 1 1 auto;
  min-width: 60px;
  max-width: 120px;
  justify-content: center;
}

.house-cell:hover {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.house-cell.selected {
  border-color: #409eff;
  background-color: #409eff;
  color: #fff;
}

.house-cell.occupied {
  border-color: #f56c6c;
  background-color: #fef0f0;
  color: #f56c6c;
}

.house-cell.selected.occupied {
  border-color: #f56c6c;
  background-color: #f56c6c;
  color: #fff;
}

.house-number {
  font-weight: 500;
  cursor: pointer;
  transition: color 0.3s;
}

.house-number:hover {
  color: #40a9ff;
  text-decoration: underline;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 房源详情侧滑面板样式 */
.house-detail-content {
  padding: 20px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

/* 批量编辑对话框样式 */
.batch-edit-info {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .units-container {
    flex-direction: column;
  }

  .unit-section {
    flex: 1 1 auto;
    min-width: auto;
    max-width: 100%;
  }
}

@media (max-width: 900px) {
  .person-container {
    flex-direction: column;
    align-items: stretch;
    padding: 0 4px;
  }

  .building-content {
    padding: 10px;
  }

  .units-container {
    flex-direction: column;
  }

  .unit-section {
    flex: 1 1 auto;
    min-width: auto;
    max-width: 100%;
  }

  :deep(.el-table .el-table__cell) {
    padding: 4px 0;
  }
}

/* 配套设施样式 */
.facility-selection {
  width: 100%;
}

.facility-checkbox {
  display: inline-block;
  margin: 4px 8px 4px 0;
  white-space: nowrap;
}

:deep(.facility-checkbox .el-checkbox__label) {
  font-size: 13px;
  padding-left: 6px;
}

.facility-preview {
  margin-top: 8px;
  padding: 6px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.facility-hint {
  margin-top: 6px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

/* 图片上传样式 */
.house-image-upload {
  width: 100%;
}

.upload-tip {
  margin-top: 8px;
}

.image-urls-preview {
  margin-top: 8px;
  padding: 6px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  word-break: break-all;
}

:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
